/* components */
import { 
  SettingGPTViewHeader,
  SettingGPTViewContent,
  SettingGPTViewCheckbox,
  SettingGPTViewCheckboxGroup,
  SettingGPTViewDialog
} from "@src/modules/setting/gpt/components";
import SettingGPTSettingViewRobotTable from "@src/modules/setting/gpt/views/index/table";
import SettingGPTSettingViewRobotOperate from "@src/modules/setting/gpt/views/index/operate";
import SettingGPTRobotViewName from "@src/modules/setting/gpt/views/index/name";
/* enum */
import ComponentNameEnum from "@model/enum/ComponentNameEnum";
/* hooks */
import { useBSHSettingGPTRobotList } from "@src/modules/setting/gpt/hooks";
/* model */
import { SettingGPTModuleEnum, SettingGPTRobotListFields } from "@src/modules/setting/gpt/model";
/* vue */
import { defineComponent } from "vue";
import { PropType } from "vue/types/v3-component-props";
/* types */
import Column from "@model/types/Column";
import { SettingGPTConfigType, SettingGPTRobotType } from "@src/modules/setting/gpt/types";
/* scss */
import "@src/modules/setting/gpt/views/index/open.scss";
/* util */
import platform from "@src/platform";
import { isRobotSystem, settingListFieldsToColumns } from "@src/modules/setting/gpt/utils";
import { isFalsy } from "@src/util/type";
import { openTabGptRobotEdit } from "@src/util/business/openTab";
import { getRootWindow } from "pub-bbx-utils";

type SettingGPTViewDialogComponentType = InstanceType<typeof SettingGPTViewDialog>
type SettingGPTRobotViewNameComponentType = InstanceType<typeof SettingGPTRobotViewName>

enum SettingGPTOpenViewEventEnum {
  ChangeCommonModel = 'changeCommonModel',
  ChangeModuleList = 'changeModuleList'
}

export default defineComponent({
  name: ComponentNameEnum.SettingGPTOpenView,
  emits: [
    SettingGPTOpenViewEventEnum.ChangeCommonModel,
    SettingGPTOpenViewEventEnum.ChangeModuleList
  ],
  props: {
    disabled: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    setting: {
      type: Object as PropType<SettingGPTConfigType>,
      default: () => ({})
    },
    onChangeCommonModel: {
      type: Function
    },
    onChangeModuleList: {
      type: Function
    }
  },
  setup(props, { emit }) {
    
    const { 
      initialize, 
      gptRobotList, 
      gptRobotPage,
      loading,
      onCreateGPTRobotHandler,
      onUpdateGPTRobotNameHandler,
      onDeleteGPTRobotHandler,
      onToggleHandler
    } = useBSHSettingGPTRobotList()
    
    return {
      initialize,
      onCreateGPTRobotHandler,
      onUpdateGPTRobotNameHandler,
      onDeleteGPTRobotHandler,
      onToggleHandler,
      loading,
      gptRobotList,
      gptRobotPage
    }
    
  },
  data() {
    return {
      isCreate: false,
      nameValue: '',
      currentEditRow: {} as SettingGPTRobotType
    }
  },
  computed: {
    attrs(): Record<string, any> {
      return {
        directives: [
          {
            name: 'loading',
            value: this.loading
          }
        ]
      }
    },
    columns(): Column[] {
      return settingListFieldsToColumns(SettingGPTRobotListFields)
    },
    isEdit(): boolean {
      return isFalsy(this.isCreate)
    },
    title(): string {
      return '小宝AI模型配置'
    },
    subTitle(): string {
      return "Hello，我是您的企业专属智能助手，作为一个企业AI助手，<br> 我不仅具备强大的自然语言处理技术，还能深度理解企业的业务需求，<br> 能够帮助您提高工作效率，助力您的企业实现更大的商业价值。"
    },
    moduleTitle(): string {
      return "数据来源模块"
    },
    moduleSubTitle(): string {
      return "勾选后，小宝可以通过关键词允许获取对象相关数据进行查询，可以快速给出对应的内容和建议。"
    },
    commonModelTitle(): string {
      return '使用通用模型'
    },
    commonModelSubTitle(): string {
      return '开启后，小宝AI根据知识库内容无法作答时，允许其根据通用大模型进行回答。'
    },
    dialogTitle(): string {
      return this.isEdit ? '编辑机器人' : '添加机器人'
    },
    settingGPTViewDialogComponent(): SettingGPTViewDialogComponentType {
      return this.$refs.SettingGPTViewDialog as SettingGPTViewDialogComponentType
    },
    settingGPTRobotViewNameComponent(): SettingGPTRobotViewNameComponentType {
      return this.$refs.SettingGPTRobotViewName as SettingGPTRobotViewNameComponentType
    }
  },
  mounted() {
    this.initialize()
  },
  methods: {
    descriptionButtonClickHandler() {
      platform.openLink('https://doc.shb.ltd/shb_xoqazk/ia4qctp2ly559d1m/eka8tf9wv8x43arx/xgs8aywpqgn7ymug.html')
    },
    commonModelSwitchChangeHandler(value: boolean) {
      this.onChangeCommonModelHandler(value)
    },
    moduleListChangeHandler(value: string[]) {
      this.onChangeModuleListHandler(value)
    },
    openDialog() {
      this.settingGPTViewDialogComponent.open()
    },
    closeDialog() {
      this.settingGPTViewDialogComponent.close()
    },
    onChangeCommonModelHandler(value: boolean) {
      this.$emit(SettingGPTOpenViewEventEnum.ChangeCommonModel, value)
    },
    onChangeModuleListHandler(value: string[]) {
      this.$emit(SettingGPTOpenViewEventEnum.ChangeModuleList, value)
    },
    onInputGPTRobotNameHandler(value: string) {
      this.nameValue = value
    },
    onClearGPTRobotNameHandler() {
      this.settingGPTRobotViewNameComponent.clear()
    },
    onCreateHandler() {
      this.nameValue = ''
      this.setIsCreateTrue()
      this.openDialog()
    },
    onEditHandler(row: SettingGPTRobotType) {
      this.currentEditRow = row
      this.nameValue = row.name
      this.setIsCreateFalse()
      this.openDialog()
    },
    onSettingHandler(row: SettingGPTRobotType) {
      const id = row.id
      openTabGptRobotEdit(id)
    },
    onDeleteHandler(row: SettingGPTRobotType) {
      this.onDeleteGPTRobotHandler(row)
    },
    onSwitchHandler(data: { row: SettingGPTRobotType, value: number }) {
      
      const { row, value } = data
      this.onToggleHandler(row, value).then(isSuccess => {
        
        if (isFalsy(isSuccess)) {
          return
        }
        
        // 如果是系统机器人，则需要刷新机器人列表
        const isSystem = isRobotSystem(row)
        if (isSystem) {
          const rootWindow = getRootWindow()
          rootWindow.getRobotList()
        }
        
      })
      
    },
    async onConfirmHandler() {
      
      const validated = await this.settingGPTRobotViewNameComponent.validate()
      
      if (isFalsy(validated)) {
        return
      }
      
      if (this.isEdit) {
        this.onUpdateGPTRobotNameHandlerImpl()
        return
      }
      
      this.onCreateGPTRobotHandlerImpl()
      
    },
    onCreateGPTRobotHandlerImpl() {
      
      const params = {
        name: this.nameValue
      }
      
      this.onCreateGPTRobotHandler(params).then(data => {
        
        const { isSuccess, robotId } = data
        
        if (isFalsy(isSuccess)) {
          return
        }
        
        this.onClearGPTRobotNameHandler()
        this.closeDialog()
        openTabGptRobotEdit(robotId)
        
      })
    },
    onUpdateGPTRobotNameHandlerImpl() {
      
      const params = {
        name: this.nameValue,
        id: this.currentEditRow.id
      }
      
      this.onUpdateGPTRobotNameHandler(params).then((isSuccess) => {
        
        if (isFalsy(isSuccess)) {
          return
        }
        
        this.onClearGPTRobotNameHandler()
        this.closeDialog()
        
      })
      
    },
    setIsCreate(value: boolean) {
      this.isCreate = value
    },
    setIsCreateTrue() {
      this.setIsCreate(true)
    },
    setIsCreateFalse() {
      this.setIsCreate(false)
    },
    renderDescriptionButton() {
      return (
        <el-button
          type="plain-third"
          onClick={this.descriptionButtonClickHandler}
        >
          使用说明
        </el-button>
      )
    },
    renderCommonModelSwitch() {
      return (
        <el-switch
          disabled={this.disabled}
          value={this.setting.useCommonModel}
          onChange={this.commonModelSwitchChangeHandler}
        >
        </el-switch>
      )
    },
    renderModuleList() {
      return (
        <SettingGPTViewCheckboxGroup
          value={this.setting.moduleList}
        >
          <SettingGPTViewCheckbox 
            label={SettingGPTModuleEnum.Wiki}
            disabled={true}
          >
            知识库
          </SettingGPTViewCheckbox>
        </SettingGPTViewCheckboxGroup>
      )
    }
  },
  render() {
    return (
      <div class={ComponentNameEnum.SettingGPTOpenView}>
        
        <SettingGPTViewHeader
          title={this.title}
          subTitle={this.subTitle}
        >
          <div slot="button">
            {this.renderDescriptionButton()}
          </div>
        </SettingGPTViewHeader>
        
        <SettingGPTViewContent
          {...this.attrs}
        >
          
          <SettingGPTSettingViewRobotOperate
            onAdd={this.onCreateHandler}
          >
          </SettingGPTSettingViewRobotOperate>
          
          <SettingGPTSettingViewRobotTable
            columns={this.columns}
            value={this.gptRobotList}
            onDelete={this.onDeleteHandler}
            onEdit={this.onEditHandler}
            onSetting={this.onSettingHandler}
            onSwitch={this.onSwitchHandler}
          >
          </SettingGPTSettingViewRobotTable>
          
        </SettingGPTViewContent>
        
        <SettingGPTViewDialog
          title={this.dialogTitle}
          ref="SettingGPTViewDialog"
          onConfirm={this.onConfirmHandler}
        >
          <SettingGPTRobotViewName
            ref="SettingGPTRobotViewName"
            value={this.nameValue}
            onInput={this.onInputGPTRobotNameHandler}
          >
          </SettingGPTRobotViewName>
        </SettingGPTViewDialog>
        
      </div>
    )
  }
});